package com.vastcom.sbjwt.service.impl;

import com.vastcom.sbjwt.model.User;
import com.vastcom.sbjwt.repository.UserRepository;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;



@Service
public class CustomUserDetailsService implements UserDetailsService {
  protected final Log LOGGER= LogFactory.getLog(getClass());
  @Autowired
  private UserRepository userRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;
  @Autowired
  private AuthenticationManager authenticationManager;






    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user=userRepository.findUserByUsername(s);
        if(user==null){
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", s));
        }
        else {
            return user;
        }

    }


    public void changePassword(String oldPassword,String newPassword){
        Authentication currentUser= SecurityContextHolder.getContext().getAuthentication();
        String username=currentUser.getName();
        if(authenticationManager!=null){
            LOGGER.debug("Re-authenticating user '"+username+" for password change request");
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username,oldPassword));
        }
        else{
            LOGGER.debug("No autentication manager set,can't change password");
            return;
        }

        LOGGER.debug("changing password for user"+username);
        User user =(User) loadUserByUsername(username);
        user.setPassword(passwordEncoder.encode(newPassword));
        userRepository.save(user);
    }



}
